package org.zcl.service.factory;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.zcl.enums.PayToolEnum;
import org.zcl.service.PayService;
import org.zcl.service.convert.ChannelPayConverter;
import org.zcl.utils.ApplicationContextUtil;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author zhuchenglin
 * @since 2022/8/22 14:02
 */
@Slf4j
@Component
public class ChannelServiceFactory {

    private final Map<String, ChannelPayConverter> payConverters = Maps.newHashMap();

    @Resource
    private ApplicationContextUtil applicationContextUtil;

    public void registerChannelPayConverter(String toolCode, ChannelPayConverter converter) {
        this.payConverters.put(toolCode, converter);
    }

    public ChannelPayConverter getPayConverter(String toolCode) {
        ChannelPayConverter converter = this.payConverters.get(toolCode);
        if (converter == null) {
            throw new RuntimeException("根据支付工具编码查找ChannelPayConverter为空");
        }
        return converter;
    }

    public PayService getPayService(String toolCode) {
        PayToolEnum tool = PayToolEnum.getPayTool(toolCode);
        if (tool == null) {
            throw new RuntimeException("获取支付通道服务失败");
        }
        try {
            return (PayService) applicationContextUtil.getBean(tool.getValue());
        } catch (Exception e) { // 重新抛出自定义异常
            log.error("SpringUtil获取Bean出错", e);
            throw new RuntimeException("获取支付通道服务失败");
        }
    }
}
